package com.qyhl.module_practice.order.mine;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeOrderBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathConstant.PRACTICE_ORDER_MINE)
public class PracticeOrderMineActivity extends BaseActivity implements PracticeOrderMineContract.PracticeOrderMineView {
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private String volId;

    private String phone;

    private PracticeOrderMinePresenter mPresenter;

    private CommonAdapter commonAdapter;

    private List<PracticeOrderBean> mDataList = new ArrayList<>();

    private int page = 1;

    private boolean isVolunteer;

    private String instId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.WHITE);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }


    }

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_my_order;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new PracticeOrderMinePresenter(this);
        volId = getIntent().getStringExtra("id");
        phone = getIntent().getStringExtra("userName");
        isVolunteer = getIntent().getBooleanExtra("isVolunteer", false);
        instId = getIntent().getStringExtra("instId");
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        if (isVolunteer) {
            mPresenter.getList(volId, page + "");
        } else {
            mPresenter.getPublic(phone, page + "");
        }
    }

    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new LinearLayoutManager(this));

        recycleView.setAdapter(commonAdapter = new CommonAdapter<PracticeOrderBean>(this, R.layout.practice_item_my_order, mDataList) {
            @SuppressLint("SetTextI18n")
            @Override
            protected void convert(ViewHolder holder, final PracticeOrderBean bean, int position) {
                holder.setText(R.id.title, bean.getDetail());
                holder.setText(R.id.type_name, bean.getTypeName());
                holder.setText(R.id.address, "地址：" + bean.getAddress());

                switch (bean.getStatus()) {
                    case 0:
                        holder.setImageResource(R.id.status, R.drawable.practice_order_wait_icon);
                        break;
                    case 1:
                        holder.setImageResource(R.id.status, R.drawable.practice_order_refuse_icon);
                        break;
                    case 2:
                        holder.setImageResource(R.id.status, R.drawable.practice_order_going_icon);
                        break;
                    case 3:
                        holder.setImageResource(R.id.status, R.drawable.practice_order_ready_icon);
                        break;
                    default:
                        holder.setImageResource(R.id.status, R.drawable.practice_order_going_icon);
                        break;
                }


                if (bean.getImages() != null && bean.getImages().size() > 0) {
                    holder.setVisible(R.id.pic_layout, true);
                    final RoundedImageView pic_one = holder.getView(R.id.pic_one);
                    final RoundedImageView pic_two = holder.getView(R.id.pic_two);
                    RoundedImageView pic_three = holder.getView(R.id.pic_three);
                    final RelativeLayout pic_three_layout = holder.getView(R.id.pic_three_layout);
                    TextView pic_num = holder.getView(R.id.pic_num);

                    switch (bean.getImages().size()) {
                        case 1:
                            pic_one.setVisibility(View.VISIBLE);
                            pic_two.setVisibility(View.INVISIBLE);
                            pic_three_layout.setVisibility(View.INVISIBLE);
                            pic_num.setVisibility(View.GONE);
                            setImage(pic_one, bean.getImages().get(0).getUrl());
                            break;
                        case 2:
                            pic_one.setVisibility(View.VISIBLE);
                            pic_two.setVisibility(View.VISIBLE);
                            pic_three_layout.setVisibility(View.INVISIBLE);
                            pic_num.setVisibility(View.GONE);
                            setImage(pic_one, bean.getImages().get(0).getUrl());
                            setImage(pic_two, bean.getImages().get(1).getUrl());
                            break;
                        case 3:
                            pic_one.setVisibility(View.VISIBLE);
                            pic_two.setVisibility(View.VISIBLE);
                            pic_three_layout.setVisibility(View.VISIBLE);
                            pic_num.setVisibility(View.GONE);
                            setImage(pic_one, bean.getImages().get(0).getUrl());
                            setImage(pic_two, bean.getImages().get(1).getUrl());
                            setImage(pic_three, bean.getImages().get(2).getUrl());
                            break;
                        default:
                            pic_one.setVisibility(View.VISIBLE);
                            pic_two.setVisibility(View.VISIBLE);
                            pic_three_layout.setVisibility(View.VISIBLE);
                            pic_num.setVisibility(View.VISIBLE);
                            setImage(pic_one, bean.getImages().get(0).getUrl());
                            setImage(pic_two, bean.getImages().get(1).getUrl());
                            setImage(pic_three, bean.getImages().get(2).getUrl());
                            pic_num.setText("+" + bean.getImages().size());
                            break;
                    }

                    pic_one.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MNImageBrowser.showImageBrowser(PracticeOrderMineActivity.this, pic_one, 0, getImageList(bean));
                        }
                    });

                    pic_two.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MNImageBrowser.showImageBrowser(PracticeOrderMineActivity.this, pic_two, 1, getImageList(bean));
                        }
                    });

                    pic_three_layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            MNImageBrowser.showImageBrowser(PracticeOrderMineActivity.this, pic_three_layout, 2, getImageList(bean));
                        }
                    });

                } else {
                    holder.setVisible(R.id.pic_layout, false);
                }

                if (bean.getActivity() != null && bean.getActivity().getName() != null) {
                    holder.setVisible(R.id.act_layout, true);
                    holder.setText(R.id.act_title, bean.getActivity().getName());
                } else {
                    holder.setVisible(R.id.act_layout, false);
                }

            }

        });
    }

    private void setListeners() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                if (isVolunteer) {
                    mPresenter.getList(volId, page + "");
                } else {
                    mPresenter.getPublic(phone, page + "");
                }
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                if (isVolunteer) {
                    mPresenter.getList(volId, page + "");
                } else {
                    mPresenter.getPublic(phone, page + "");
                }
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isVolunteer) {
                    mPresenter.getList(volId, page + "");
                } else {
                    mPresenter.getPublic(phone, page + "");
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", mDataList.get(position));
                bundle.putString("instId",instId);
                RouterManager.router(ARouterPathConstant.PRACTICE_ORDER_DETAIL,bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    private void setImage(RoundedImageView cover, String url) {
        Glide.with(this)
                .load(url)
                .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(cover);
    }

    private ArrayList<String> getImageList(PracticeOrderBean bean) {
        ArrayList<String> result = new ArrayList<>();
        for (int i = 0; i < bean.getImages().size(); i++) {
            result.add(bean.getImages().get(i).getUrl());
        }
        return result;
    }

    @Override
    public void setList(List<PracticeOrderBean> beanList, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        loadMask.setStatus(LoadingLayout.Success);
        page++;
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @OnClick(R2.id.back_btn)
    public void onViewClicked() {
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_ORDER_MINE);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_ORDER_MINE);
    }

}
